import {del, get, put} from './http.js';

$(document).ready(function () {
    // 初始化购物车
    init();
});

async function init() {
    // 获取购物车数据
    cartData = await get('/api/cart/list');
    // 渲染购物车
    renderCart();
    // 更新总计
    updateTotal();
    // 更新全选状态
    updateSelectAll();

    // 全选/取消全选
    $('#selectAll, #selectAllBottom').change(function () {
        const selected = $(this).prop('checked');
        $('#selectAll, #selectAllBottom').prop('checked', selected);
        $('.cart-item input[type="checkbox"]').prop('checked', selected);
        updateCartData();
        updateTotal();

        put('/api/cart/select-all', {selected});
    });

    // 删除选中商品
    $('.delete-selected').click(function () {
        if (confirm('确定要删除选中的商品吗？')) {
            cartData = cartData.filter(item => item.selected);
            let reqBody = {
                itemIds: cartData.map(item => item.id)
            }
            del(`/api/cart/delete`, reqBody).then(res => {
                init();
            })
        }
    });

    // 去结算
    $('#btnCheckout').click(function () {
        const selectedItems = cartData.filter(item => item.selected);
        if (selectedItems.length === 0) {
            alert('请选择要结算的商品');
            return;
        }
        // 购物车项ID
        let itemIdArr = selectedItems.map(item => item.itemId);
        // 构建URL参数
        let urlParams = `itemId=${itemIdArr}&from=cart`;
        window.location.href = `order.html?${urlParams}`;
    });
}

// 渲染购物车
function renderCart() {
    const $cartList = $('.cart-list');
    $cartList.empty();
    cartData.forEach(item => {
        const itemHtml = `
            <div class="cart-item" data-id="${item.id}">
                <label class="checkbox-wrapper">
                    <input data-id="${item.id}" type="checkbox" ${item.selected ? 'checked' : ''}>
                </label>
                <div class="product-img">
                    <img src="${item.image}" alt="${item.title}">
                </div>
                <div class="product-info">
                    <div class="product-title">${item.title}</div>
                    <div class="product-spec">${item.spec}</div>
                </div>
                <div class="price">¥${item.price.toFixed(2)}</div>
                <div class="count-control">
                    <button class="btn-decrease" data-id="${item.id}">-</button>
                    <input type="text" value="${item.count}" min="1" max="${item.stock}" data-id="${item.id}">
                    <button class="btn-increase" data-id="${item.id}">+</button>
                </div>
                <div class="total">¥${(item.price * item.count).toFixed(2)}</div>
                <div class="action">
                    <a href="javascript:;" class="btn-delete">删除</a>
                </div>
            </div>
        `;
        $cartList.append(itemHtml);
    });
    // 绑定事件
    bindEvents();
}

// 绑定事件
function bindEvents() {
    // 商品选择
    $('.cart-item input[type="checkbox"]').change(function () {
        let itemId = $(this).data('id');
        const selected = $(this).prop('checked');
        put('/api/cart/select-unselect', {itemId, selected}).then(res => {
            updateCartData();
            updateTotal();
            updateSelectAll();
        });
    });

    // 减少数量
    $('.btn-decrease').click(function () {
        const $input = $(this).next('input');
        let quantity = parseInt($input.val());
        if (quantity > 1) {
            $input.val(--quantity);
            updateItemCount($(this).closest('.cart-item'), quantity);

            const itemId = $(this).data('id');
            put(`/api/cart/update-quantity`, {itemId, quantity}).then(res => {
            });
        }
    });

    // 增加数量
    $('.btn-increase').click(function () {
        const $input = $(this).prev('input');
        let quantity = parseInt($input.val());
        const max = parseInt($input.attr('max'));
        // if (count < max) {
        $input.val(++quantity);
        updateItemCount($(this).closest('.cart-item'), quantity);
        // }
        const itemId = $(this).data('id');
        put(`/api/cart/update-quantity`, {itemId, quantity}).then(res => {
        });
    });

    // 直接输入数量
    $('.count-control input').change(function () {
        let quantity = parseInt($(this).val());
        const max = parseInt($(this).attr('max'));
        if (isNaN(quantity) || quantity < 1) quantity = 1;
        // if (count > max) count = max;
        $(this).val(quantity);
        updateItemCount($(this).closest('.cart-item'), quantity);
        const itemId = $(this).data('id');
        put(`/api/cart/update-quantity`, {itemId, quantity}).then(res => {
        });
    });

    // 删除商品
    $('.btn-delete').click(function () {
        if (confirm('确定要删除该商品吗？')) {
            const $item = $(this).closest('.cart-item');
            const id = $item.data('id');
            // 删除商品
            let reqBody = {
                itemIds: [id]
            }
            del(`/api/cart/delete`, reqBody).then(res => {
                init();
                Notify.success('删除成功');
            })
        }
    });
}

// 更新商品数量
function updateItemCount($item, count) {
    const id = $item.data('id');
    const item = cartData.find(item => item.id == id);
    if (item) {
        item.count = count;
        $item.find('.total').text(`¥${(item.price * count).toFixed(2)}`);
        updateTotal();
    }
}

// 更新购物车数据
function updateCartData() {
    $('.cart-item').each(function () {
        const id = $(this).data('id');
        const selected = $(this).find('input[type="checkbox"]').prop('checked');
        const item = cartData.find(item => item.id == id);
        if (item) {
            item.selected = selected;
        }
    });
}

// 更新总计
function updateTotal() {
    let selectedCount = 0;
    let totalPrice = 0;

    cartData.forEach(item => {
        if (item.selected) {
            selectedCount += item.count;
            totalPrice += item.price * item.count;
        }
    });

    $('#selectedCount').text(selectedCount);
    $('#totalPrice').text(`¥${totalPrice.toFixed(2)}`);
}

// 更新全选状态
function updateSelectAll() {
    const allSelected = cartData.length > 0 && cartData.every(item => item.selected);
    $('#selectAll, #selectAllBottom').prop('checked', allSelected);
} 